﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;
using RssFeeds;

/*
Developed By: Jyoti Seth
Developed On: 5th Feb 2011
Description: This code displays the Project RSS Feeds contents
Modified On: 14th Jun 2011
Description: Need to add Title field in the list and remove category and description fields. Also Title field
 * will be displayed in the treeview
*/
namespace RSSFeeds.RSS_Feeds
{
    public partial class RSS_FeedsUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Create RSS Feeds list
                RssFeedsList();

                ViewState["SelNode"] = "";
                PopulateTreeViewControl();
            }

            TreeView tview = Page.Master.FindControl("tvRssFeeds") as TreeView;

            if (ViewState["SelNode"] != null)
            {
                if (ViewState["SelNode"].ToString() != "")
                {
                    TraverseTreeView();
                }
            }

        }

        /* Fetch and Populate all the RSS Feeds */
        private DataTable GetRssFeeds()
        {
            DataTable dtRssFeeds = new DataTable();
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["RSS Feeds"];
                        SPListItemCollection itemColl;
                        SPQuery query = new SPQuery();
                        query.Query =
                          "<OrderBy><FieldRef Name=\"Created\" Ascending=\"FALSE\"></FieldRef></OrderBy>";

                        itemColl = list.GetItems(query);
                        //itemColl = list.GetItems();
                        dtRssFeeds.Columns.Add("Id", typeof(String));
                        dtRssFeeds.Columns.Add("Title", typeof(String));
                        dtRssFeeds.Columns.Add("RssFeedUrl", typeof(String));
                        dtRssFeeds.Columns.Add("RssFeedUrlDesc", typeof(String));

                        if (itemColl.Count > 0)
                        {
                            for (int icount = 0; icount < itemColl.Count; icount++)
                            {
                                SPListItem listItem = itemColl[icount];
                                DataRow drRssFeeds = dtRssFeeds.NewRow();

                                drRssFeeds["Id"] = listItem["ID"].ToString();
                                drRssFeeds["Title"] = listItem["Title"].ToString();

                                SPFieldUrlValue value = new SPFieldUrlValue(listItem["URL"].ToString());

                                drRssFeeds["RssFeedUrl"] = value.Url;

                                if (value.Description == "")
                                    drRssFeeds["RssFeedUrlDesc"] = value.Url;
                                else
                                    drRssFeeds["RssFeedUrlDesc"] = value.Description;

                                dtRssFeeds.Rows.Add(drRssFeeds);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            return dtRssFeeds;
        }

        // This method is used to populate the TreeView Control with RSS Feeds 
        private void PopulateTreeViewControl()
        {
            try
            {
                int counter = 0;
                string siteUrl;
                string mainTitle = String.Empty;
                TreeNode titleNode = null;
                TreeNode parentNode = null;
                DataTable dtRssFeeds = new DataTable();
                dtRssFeeds = GetRssFeeds();
                if (dtRssFeeds.Rows.Count > 0)
                {
                    foreach (DataRow row in dtRssFeeds.Rows)
                    {
                        try
                        {
                            // This will fetch the domain name of the site of RSS Feed link
                            siteUrl = row["RssFeedUrl"].ToString();
                            siteUrl = siteUrl.Replace("http://", "");
                            siteUrl = "http://" + siteUrl.Substring(0, siteUrl.IndexOf("/") + 1);

                            mainTitle = row["Title"].ToString();

                            // Fetch the RSS Feed details
                            XDocument rssFeed = XDocument.Load(row["RssFeedUrl"].ToString());

                            var posts = (from item in rssFeed.Descendants("item")
                                         orderby ConvertDateTime(item.Element("pubDate") != null ? item.Element("pubDate").Value : String.Empty) descending
                                         select new Feeds
                                         {
                                             title = item.Element("title") != null ? item.Element("title").Value : String.Empty,
                                             link = item.Element("link") != null ? item.Element("link").Value : String.Empty,
                                             description = item.Element("description") != null ? item.Element("description").Value : String.Empty,
                                             siteURL = siteUrl
                                         });

                            //list feed data read
                            List<Feeds> newsList = new List<Feeds>();
                            newsList = posts.ToList();

                            string rssfeedMainTitle, rssfeedTitle, rssfeedDesc, rssfeedLink;
                            rssfeedMainTitle = String.Empty;

                            foreach (var listitem in newsList)
                            {
                                try
                                {
                                    rssfeedTitle = listitem.title.ToString();
                                    rssfeedDesc = UpdateDescription(siteUrl, listitem.description.ToString().Trim());

                                    rssfeedLink = listitem.link.ToString();

                                    if (rssfeedMainTitle != mainTitle)
                                    {
                                        titleNode = new TreeNode(mainTitle, counter.ToString() + "Title");
                                        titleNode.SelectAction = TreeNodeSelectAction.Select;
                                        titleNode.NavigateUrl = row["RssFeedUrl"].ToString();
                                        titleNode.Target = "_blank";
                                    }
                                    parentNode = new TreeNode(rssfeedTitle, counter.ToString());
                                    parentNode.SelectAction = TreeNodeSelectAction.Select;
                                    parentNode.NavigateUrl = rssfeedLink;
                                    parentNode.Target = "_blank";
                                    parentNode.Collapse();
                                    titleNode.ChildNodes.Add(parentNode);
                                    titleNode.Collapse();
                                    if (rssfeedMainTitle != mainTitle)
                                    {
                                        tvRssFeeds.Nodes.Add(titleNode);
                                    }
                                    TreeNode childNode = new TreeNode(rssfeedDesc, counter.ToString() + "Desc");
                                    parentNode.ChildNodes.Add(childNode);
                                    childNode.SelectAction = TreeNodeSelectAction.None;

                                    rssfeedMainTitle = mainTitle;
                                    counter = counter + 1;
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    parentNode.CollapseAll();
                    titleNode.CollapseAll();
                }
                else
                {
                    lblMessage.Text = "There are no items to show in this view.";
                }
            }
            catch
            {
            }
        }

        //This will traverse through each node (RSS Feed Title) of the tree and mark the clicked node as selected node
        private void TraverseTreeView()
        {
            //Create a TreeNode to hold the Parent Node
            TreeNode node = new TreeNode();
            TreeNode nodeChild = new TreeNode();

            //Loop through the Parent Nodes
            for (int k = 0; k < tvRssFeeds.Nodes.Count; k++)
            {
                //Store the Parent Node in temp
                node = tvRssFeeds.Nodes[k];

                //Now Loop through each of the child nodes in this parent node i.e.temp
                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    nodeChild = node.ChildNodes[i];
                    if (nodeChild.Value.ToString() == ViewState["SelNode"].ToString())
                        nodeChild.Selected = true;
                }
            }
        }

        // Function will replace the virtual path in the rss feed to the actual path of the site
        public string UpdateDescription(string siteUrl, string description)
        {
            string updDesc;
            updDesc = description.Replace("src=\"/", "src=\"" + siteUrl);
            return updDesc;
        }


        // Function will return default PubDate value if the pubDate is null or not a valid date
        public DateTime ConvertDateTime(string pubDate)
        {
            DateTime retPubDate;
            if (DateTime.TryParse(pubDate, out retPubDate))
                return retPubDate;
            else
                return new DateTime(2000);
        }

        // Create RSS Feeds list
        private void RssFeedsList()
        {
            try
            {
                Boolean isListExists;

                isListExists = SharepointManager.ListExists(SPContext.Current.Web, "RSS Feeds");

                if (!isListExists)
                {
                    SharepointManager.CreateNewList("RSS Feeds", "RSS Feeds List", SPListTemplateType.GenericList);
                }

                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb webCurrent = site.OpenWeb())
                    {
                        webCurrent.AllowUnsafeUpdates = true;
                        SPList list = webCurrent.Lists["RSS Feeds"];
                        list.OnQuickLaunch = true;

                        Boolean isFieldExists = list.Fields.ContainsField("URL");

                        if (list != null && !isFieldExists)
                        {

                            list.Fields.Add("URL", SPFieldType.URL, true);
                            list.Update();

                            SPView view = list.DefaultView;
                            view.ViewFields.Add("URL");
                            view.ViewFields.Add("Created By");
                            view.ViewFields.Add("Created");

                            //// Added by Jyoti on 7 march 2011 to show the most recent record to be appear at top view.Query = "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";
                            view.Query = "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";

                            view.Update();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        protected void hlkAddLink_Click(object sender, EventArgs e)
        {
            SPSite webSite = SPContext.Current.Site; //get the current site
            string  urlCurrent = webSite.Url;
            Response.Redirect(urlCurrent + "/Lists/RSS Feeds/AllItems.aspx ");
        }
    }
}
